import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import java.util.HashSet;

class Server extends ServerSocket implements Runnable {
	private HashSet<Thread> threads = new HashSet<Thread>();
	private HashSet<Service> services = new HashSet<Service>();

	private Control control;

	public Server(InetAddress bindAddress, int port, Control control) throws Exception
	{
		super(port, 50, bindAddress);
		//System.out.println("Server, Server()");
		this.control = control;
		this.control.addTextPane();
	}

	public boolean isAlive()
	{
		System.out.println("Server, isAlive()");
		return !services.isEmpty();
	}

	public void removeService(Service service)
	{
		this.services.remove(service);
		this.threads.remove(service);
		System.out.println("Server, remoteService()");
	}

	public void run()
	{
		System.out.println("Server, run()");

		while(true) {
			try {
				Socket socket = this.accept();

				control.log("Accepting: " + this, 0);
				control.log("Incoming: " + socket, 0);

				control.addTextPane();
				control.log("New service (id "+(this.services.size()+1)+")\n", 0);

				Service service = new Service(socket, control, this.services.size()+1, this);
				services.add(service);

				Thread thread = new Thread(service);
				threads.add(thread);

				thread.start();
			} catch (Exception e) {
				//control.log(e.getMessage(), 0);
			}
		}
	}
	
	public void stop() {
		for(Service s : services) {
			s.closeSocket();
			removeService(s);
		}
		
		try {
			this.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}